package com.util;

import android.content.Context;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class FileUtil {
    public static void Save(Context context,String name,String data) throws IOException {
        File file = new File(context.getFilesDir(), name);
        try{
            FileOutputStream o=new FileOutputStream(file);
            o.write(data.getBytes(StandardCharsets.UTF_8));
            o.flush();
            o.close();
        }catch (IOException e){
            throw e;
        }
    }
    public static void Delete(Context context,String name) {
        File file = new File(context.getFilesDir(), name);
        if(file.exists()){
            file.delete();
        }
    }
    public static String Read(Context context,String name) throws IOException {
        File file = new File(context.getFilesDir(), name);
        FileInputStream i=null;
        String data;
        try{
            long len=file.length();
            byte[] bytes=new byte[len<1024? (int) len :1024];
            i=new FileInputStream(file);
            long size=0;
            int count;
            while ((count=i.read(bytes))>0){
                if(len-size<bytes.length){
                    bytes=new byte[(int) (len-size)];
                }
                size+=count;
            }
            data=new String(bytes);
        }catch (IOException e){
            return "";
        }finally {
            if(i!=null)i.close();
        }
        return data;
    }
}
